<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\enum\account\PayeeType;
use app\common\enum\account\PaymentPayeeType;
use app\common\exception\BaseException;
use app\common\model\AccountRecord;
use app\common\model\DealerCharge;
use app\common\model\Refund;
use app\common\model\Salesman;
use app\common\model\Dealer;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\AccountPaymentOrder as AccountPaymentOrderModel;
use think\App;
use app\Request;
use think\response\Json;

/**
 * @ControllerAnnotation(title="付款单")
 */
class AccountPaymentOrder extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new AccountPaymentOrderModel();
        $this->each  = true;
    }

    /**
     * 获取默认回显金额
     */
    public function amount(): Json
    {
        $get = $this->request->get();
        if (empty($get['payee_id']) && empty($get['payee_type'])) return $this->error('请选择支付类型和收款方ID');
        $model  = (new AccountRecord())->where('company_id', $this->companyId)
                                       ->where('payee_type', $get['payee_type'])
                                       ->where('payee_id', $get['payee_id']);
        $amount = 0;
        if ($get['pay_type'] == 1) {
            $amount = $model->value('return_money');
        }
        if ($get['pay_type'] == 2) {
            $amount = $model->value('fz_money');
        }
        return $this->success(['amount' => $amount]);
    }

    public function each($list)
    {
        return $list->each(function ($item)
        {
            // 处理人
            $item->handler = $item->handler()->value('username');
            if ($item->payee_type == PaymentPayeeType::SALES) {
                $item->payee_name = $item->salesman()->value('rename');
            } elseif ($item->payee_type == PaymentPayeeType::DEALER) {
                $item->payee_name = $item->dealer()->value('name');
            } else {
                $item->payee_name = '未知';
            }
            if ($item->store_id) {
                $item->store_name = $item->store()->value('name');
            }
        });
    }

    /**
     * @NodeAnnotation (title="新增")
     * @throws BaseException
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $this->sceneValidate($post, 'add');
        $post['company_id'] = $this->companyId;
        $post['handler_id'] = $this->uid;
        $post['no']         = generateOrderNo('FK');
        try {
            $this->model->transaction(function () use ($post)
            {
                $accountRecord = AccountRecord::where(['payee_id' => $post['payee_id'], 'payee_type' => $post['payee_type']])
                                              ->find();
                if (!$accountRecord) throw new BaseException(['message' => '对账单信息不存在']);
                $post['account_id'] = $accountRecord->id;
                if($post['payee_type'] == PayeeType::SALESMAN){
                    $payee_name = Salesman::where('id',$post['payee_id'])->value('rename');
                }else if($post['payee_type'] == PayeeType::DEALER){
                    $payee_name = Dealer::where('id',$post['payee_id'])->value('name');
                }
                $post['payee_name'] = $payee_name ?? '';
                $this->model->save($post);
                if ($post['pay_type'] == 1) {
                    $accountRecord->inc('return_money', $post['amount'])->save();
                    // 更新退款状态
                    $record = (new Refund())->where('account_record_id', $accountRecord->id)->find();
                    if(!$record) throw new BaseException(['message' => '退款单不存在']);
                    (new Refund())->where('account_record_id', $accountRecord->id)->save([
                                   'status'     => 2,
                                   'check_time' => time()
                           ]);
                } else {
                    // 更新分账明细里的状态和时间
                    (new DealerCharge())->where('account_record_id', $accountRecord->id)->save([
                        'status'     => 2,
                        'check_time' => time()
                    ]);
                    $accountRecord->dec('fz_money', $post['amount'])->inc('real_money',$post['amount'])->save();
                }
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }
}